from machine import Timer, WDT, Pin
import network
import gc
from drivers.ds18b20 import DS18B20
from drivers.dht11 import DHT11
import utils


class TimerController:
	# 定义定时器触发时间，单位：毫秒
	TIMER_PERIOD_1000 = 1000
	TIMER_PERIOD_2000 = 2100

	def __init__(self):
		self._led = Pin(2, Pin.OUT, value=1)
		self._watch_dog = WDT()
		self._watch_dog.feed()
		self._sensor1 = DS18B20(4)
		self._sensor2 = DHT11(5)
		self._station = network.WLAN(network.STA_IF)
		self._wifi_status_timer = Timer(0)
		self._led_blink_timer = Timer(1)
		self._get_temperature_timer = Timer(2)

	def start_get_temperature_timer(self, period=5*60*1000):
		self._get_temperature_timer.init(
			mode=Timer.PERIODIC,
			period=period,
			callback=self._get_temperature_cb
		)

		gc.collect()

	def _get_temperature_cb(self, timer):
		self._watch_dog.feed()

		try:
			temp1 = self._sensor1.get_temperature()
			temp2 = self._sensor2.get_temperature()

			if temp1 is not None:
				print("ds18b20 temp:", temp1, end=", ")
			else:
				temp1 = 255
				print("error", end=", ")

			print("dht11 temp:", temp2)

			utils.update_temperature(temp1, temp2)

			gc.collect()
		except Exception as e:
			utils.log(e)

	def start_wifi_status_timer(self):
		self._start_led_blink_timer()

		self._wifi_status_timer.init(
			mode=Timer.PERIODIC,
			period=self.TIMER_PERIOD_1000,
			callback=self._check_wifi_status_cb
		)

		gc.collect()

	def _check_wifi_status_cb(self, timer):
		if self._station.isconnected():
			self._led_blink_timer.deinit()
			self._led.value(1)

		gc.collect()

	def _start_led_blink_timer(self):
		self._led_blink_timer.init(
			mode=Timer.PERIODIC,
			period=self.TIMER_PERIOD_1000,
			callback=lambda timer: self._led.value(not self._led.value())
		)

		gc.collect()

	@property
	def get_distance_status(self):
		return 0

	@property
	def get_relay_status(self):
		return 1
